package top.broncho.mvvm.util

import java.security.MessageDigest

/**
 * md5加密字符串
 * md5使用后转成16进制变成32个字节
 */
fun String.md5(): String {
    val digest = MessageDigest.getInstance("MD5")
    val result = digest.digest(toByteArray())
    return result.toHex()
}

fun String.sha1(): String {
    val digest = MessageDigest.getInstance("SHA-1")
    val result = digest.digest(toByteArray())
    return result.toHex()
}

fun String.sha256(): String {
    val digest = MessageDigest.getInstance("SHA-256")
    val result = digest.digest(toByteArray())
    return result.toHex()
}

private fun ByteArray.toHex(): String {
    //转成16进制后是32字节
    return with(StringBuilder()) {
        forEach {
            val hex = it.toInt() and (0xFF)
            val hexStr = Integer.toHexString(hex)
            if (hexStr.length == 1) {
                append("0").append(hexStr)
            } else {
                append(hexStr)
            }
        }
        toString()
    }
}
